export default {
  namespaced: true, // 命令空间，实现模块私有，区分不同的模块
  state: {
    cartList: [] // 购物车列表
  },
  getters: {
    getCartList (state) {
      return state.cartList
    },
    isAllChecked (state) {
      // every 所有的都为真，则为真，有一个为假，则为假
      return state.cartList.every(item => item.state)
    },
    getTotalCount (state) {
      /**
       * 参数1：处理函数（参数1：计算的结果，参数2：遍历到的每一项就是商品对象）
       * 参数2：初始值
       */
      return state.cartList.reduce((total, item) => total + item.number, 0)
    },
    getTotalAmount (state) {
      return state.cartList
        .filter(item => item.state)
        .reduce((total, item) => total + item.number * item.price, 0)
    }
  },
  mutations: {
    // payload ===> {proid,proname,img,price,number,state}
    addToCart (state, payload) {
      // 查找cartList中是否存在相同的商品
      const oldGoods = state.cartList.find(item => item.proid === payload.proid)
      if (oldGoods) {
        // 找到了
        oldGoods.number += payload.number
      } else {
        state.cartList.push(payload)
      }
    },
    // payload ===> {proid,state}
    // 修改选中状态
    changeGoodsState (state, payload) {
      const oldGoods = state.cartList.find(item => item.proid === payload.proid)
      if (oldGoods) {
        oldGoods.state = payload.state
      }
    },
    // payload ===> {proid,number}
    // 修改数量
    changeGoodsNumber (state, payload) {
      const oldGoods = state.cartList.find(item => item.proid === payload.proid)
      if (oldGoods) {
        oldGoods.number = payload.number
      }
    },
    // payload ===> proid
    deleteGoods (state, payload) {
      // 方式1：找到它在数组中的索引，然后调用数组的 splice 方法删除
      // 方式2：使用filter，把过滤完的数组赋值给原数组
      state.cartList = state.cartList.filter(item => item.proid !== payload)
    },
    // payload ===> state
    selectAllOrNot (state, payload) {
      state.cartList.forEach(item => {
        item.state = payload
      })
    }
  }
}
